<template>
  <div>
    <van-nav-bar title="IT资讯 - 登录" />
    <div>
      <van-form @submit="onSubmit" style="margin-top: 16px;">
        <van-field
          v-model="user.mobile"
          name="mobile"
          label=" 手机号"
          placeholder="请输入11位手机号" required
          :rules="[{ required: true, message: '请填写正确的手机号', pattern : /^1[3-9]\d{9}$/ }]"
        />
        <van-field
          v-model="user.code"
          type="password"
          name="code"
          label=" 密码"
          placeholder="请输入6位密码" required
          :rules="[{ required: true, message: '请填写正确的密码',
          pattern: /^\d{6}$/ }]"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" style="background-color: skyblue" :disabled="isLoading"  :loading="isLoading" loading-text="加载中...">登录</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { Toast } from 'vant'
import { setToken } from '@/utils/token.js'
export default {
  data () {
    return {
      user: {
        mobile: '18888888888', // 手机号
        code: '246810' // 验证码(246810)
      },
      isLoading: false
    }
  },
  methods: {
    // 提交方法(form 整体通过验证才会触发)
    async onSubmit (values) {
      console.log('submit', values)
      // 状态设置true
      this.isLoading = true

      try {
        const res = await loginAPI(this.user)
        console.log(res)
        // Notify({ type: 'success', message: '登录成功' })
        Toast.success('登录成功')
        setToken(res.data.data.token)

        localStorage.setItem('refresh_token', res.data.data.refresh_token)

        this.$router.replace({
          path: '/layout/home'
        })
      } catch (err) {
        // Notify({ type: 'danger', message: '账号或密码错误' })
        Toast.fail('账号或密码错误')
      }
      this.isLoading = false // 网络请求完成无论诚功/报情，把状态关掉
    }
  }
}
</script>

<style scoped lang='less'>
// .van-nav-bar {
//   background-color: skyblue;
// }

// // 要修改组件内样式,如果用了scoped, 选择器前加/deep/即可
// /deep/ .van-nav-bar__title {
//   color: #fff;
// }
</style>
